<template>
	<view class="container">
		
		<view class='header'>
			<view class="icon iconfont icon-logo-wechat"></view>
		</view>

		<view class='content'>
			<view>申请获取以下权限</view>
			<text>获得你的公开信息(昵称，头像等)</text>
		</view>
		
		<!-- <button class='bottom' type='primary' @click="toClear">
			清除数据
		</button> -->
		
		<template v-if="status == 0">
			<button class='bottom' type='primary' open-type="getUserInfo" lang="zh_CN" @getuserinfo="wxLogin">
				授权登录
			</button>
		</template>
		
		<template v-else-if="status == 1">
			<button class='bottom' type='primary' open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
				获取手机号
			</button>
		</template>
		
		<template v-else>
			<button class='bottom' type='primary' @click="toIndex">
				返回
			</button>
		</template>
	</view>
</template>

<script>
	import Storage from '@/common/scripts/storage.js'
	import config from '@/common/scripts/config.js'
	import IndexService from './service/service.js'
	import WXBizDataCrypt from '../../common/scripts/WXBizDataCrypt.js'

	export default {
		beforeCreate() {
			this.service = new IndexService()
		},
		name: 'index-login',
		data() {
			return {
				logining: false,
				appid: config.appid,
				secret: config.secret,
				openURL: config.openURL,
				provider: config.provider,
				access_token: null,
				sessionKey: null,
				status: 0,
				openID: null,
				phone: null,
				unionID: null,
				code: null,
				userInfo: null,
				encryptedData: null,
				iv: null
			}
		},
		onLoad(options) {
			let that = this
			console.log(options)
			Storage.set('back-page', options)
		},
		methods: {
			toClear() {
				this.service.clear()
			},
			toIndex() {
				uni.redirectTo({
					url: '/pages/index/index'
				})
			},
			toMyCenter() {
				let myCenter = { g: "Wap", c: "Mall", a: "myCenter", lj_page: "/wap.php" }
				Storage.set('back-page', myCenter)
				uni.redirectTo({
					url: '/pages/index/index'
				})
			},
			init() {
				let that = this
				// #ifdef MP-WEIXIN
				Storage.get('code')
					.then(function(result) {
						that.status = 0
						that.code = result.data
						that.initWx()
					})
				// #endif
			},
			initWx() {
				let that = this
				that.service.getUserInfo()
					.then(that.getUserInfoSuccess).catch(that.getUserInfoError)
					.then(that.getOpenIDSuccess).catch(that.getOpenIDError)
			},
			loginSuccess(result) {
				console.log(result)
				if (result) {
					this.status = 0
					this.code = result.code
					return this.service.getUserInfo()
				} else {
					return null
				}
			},
			loginError(err) {
				console.log(err)
				if (err) {
					return null
					this.status = 0
				}
			},
			getUserInfoSuccess(result) {
				console.log(result)
				let that = this
				if (result) {
					that.status = 1
					that.userInfo = result.userInfo
					console.log(that.code)
					return this.service.getOpenID({
						code: that.code
					})
				} else {
					this.status = 0
					return null
				}
			},
			getUserInfoError(err) {
				console.log(err)
				if (err) {
					this.status = 0
					return null
				}
			},
			getOpenIDSuccess(result) {
				let that = this
				console.log(result)
				if (result) {
					this.status = 1
					this.openID = result.openid
					this.unionID = result.unionid
					this.sessionKey = result.session_key
				}
				return null
			},
			getOpenIDError(err) {
				console.log(err)
				if (err) {
					this.status = 1
					return null
				}
			},
			getPhoneNumber(e) { //这个事件同样需要拿到e
				let that = this
				let ency = e.detail.encryptedData;
				let iv = e.detail.iv;
				let errMsg = e.detail.errMsg

				var pc = new WXBizDataCrypt(config.appid, that.sessionKey)

				var data = pc.decryptData(ency, iv)
				
				let options = {
					'phone': data.phoneNumber,
					'union_id': that.unionID,
					'nickname': that.userInfo.nickName,
					'avatar': that.userInfo.avatarUrl,
					'wxapp_openid': that.openID
				}
				
				that.service.sysLogin(options)
					.then(function(result) {
						
						console.log(result)
						if (result.hasOwnProperty('status') && result.status == 'ok') {
							that.toMyCenter()
						} else {
							if (result.hasOwnProperty('status') && result.status == 'faild' && result.msg == "授权失败，请重试") {
								that.service.sysLogin(options)
									.then(function(result) {
										console.log(result)
										if (result.hasOwnProperty('status') && result.status == 'ok') {
											that.toMyCenter()
										} else {
											uni.showToast({
												content: '用户登录失败，请与管理员联系！'
											})
											that.toIndex()
										}
									})
									.catch(function(err) {
										console.log(err)
										uni.showToast({
											content: '用户登录失败，请与管理员联系！'
										})
										that.toIndex()
									})
							} else {
								uni.showToast({
									content: '用户登录失败，请与管理员联系！'
								})
								that.toIndex()
							}
						}
					})
					.catch(function(err) {
						console.log(err)
						if (err.hasOwnProperty('status') && err.status == 'faild' && err.msg == "授权失败，请重试") {
							that.service.sysLogin(options)
								.then(function(result) {
									console.log(result)
									if (result.hasOwnProperty('status') && result.status == 'ok') {
										that.toMyCenter()
									} else {
										uni.showToast({
											content: '用户登录失败，请与管理员联系！'
										})
										that.toIndex()
									}
								})
								.watch(function(err) {
									console.log(err)
									uni.showToast({
										content: '用户登录失败，请与管理员联系！'
									})
									that.toIndex()
								})
						}
					})
			},
			wxLogin(e) {
				let that = this;
				that.logining = true;
				that.userInfo = e.detail.userInfo
				console.log(that.userInfo)
				uni.login({
					provider: that.provider,
					success: (login_res => {
						that.code = login_res.code
						that.status = 1
						that.service.getUserInfo()
							.then(that.getUserInfoSuccess).catch(that.getUserInfoError)
							.then(that.getOpenIDSuccess).catch(that.getOpenIDError)
					}),
					fail: function(err) {
						that.status = 0
					}
				})
			}
		},
		created() {
			this.init()
		}
	}
</script>

<style lang="scss">
	.container {
		display: flex;
		overflow: hidden;
		background: #fff;
		flex-direction: column;
		justify-content: center;
		height: 100vh;

		.icon-logo-wechat {
			font-size: 200upx;
			width: 200upx;
			height: 200upx;
			display: inline-block;
		}

		.demo {
			width: 200px;
			height: 200px;
		}

		.confirm-btn {
			width: 630upx;
			height: 76upx;
			line-height: 76upx;
			border-radius: 50px;
			margin-top: 70upx;
			background: #000000;
			color: #fff;
			font-size: 16upx;

			&:after {
				border-radius: 100px;
			}
		}
	}

	.header {
		margin: 90upx 90upx 90upx 50upx;
		border-bottom: 1upx solid #ccc;
		text-align: center;
		width: 650upx;
		height: 300upx;
	}

	.content {
		margin-left: 50upx;
		margin-bottom: 90upx;
	}

	.content text {
		display: block;
		color: #9d9d9d;
		margin-top: 40upx;
	}

	.bottom {
		border-radius: 80upx;
		margin: 70upx 50upx;
		font-size: 35upx;
	}
</style>
